﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Casamiel.Domain.Entity;

using Casamiel.Domain.Request;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.IC;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands.Order
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class CreateCakeOrderV2CommandHandler : BaseCommandHandler, IRequestHandler<CreateCakeOrderV2Command, BaseResult<PaymentRsp>>
	{
		//private readonly NLog.ILogger orderlogger = NLog.LogManager.GetLogger("OrderService");
		private readonly IMbrStoreRepository _mbrStoreRepository;
		private readonly IMemberCardRepository _memberCardRepository;
		private readonly ICasaMielSession _session;
		private readonly IPaymentRecordRepository _paymentRecordRepository;
		private readonly INoticeBaseRepository _noticeBase;
		private readonly IUserLogRepository _userLogRepository;
		private readonly IOrderBaseRepository _orderBaseRepository;
		private readonly IMemberCashCouponRepository _memberCashCouponRepository;
		private readonly IMemberCouponRepository _memberCouponRepository;
		private readonly string _apiName;
		public CreateCakeOrderV2CommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings,
		IMbrStoreRepository mbrStoreRepository, IUserLogRepository userLogRepository, INoticeBaseRepository noticeBaseRepository, IMemberCardRepository memberCardRepository, ICasaMielSession session, IPaymentRecordRepository paymentRecordRepository,
		IOrderBaseRepository orderBaseRepository, IMemberCashCouponRepository memberCashCouponRepository, IMemberCouponRepository memberCouponRepository) : base(netICService, httpClientFactory, settings)
		{
			_mbrStoreRepository = mbrStoreRepository;
			_memberCardRepository = memberCardRepository;
			_session = session;
			_paymentRecordRepository = paymentRecordRepository;
			_noticeBase = noticeBaseRepository;
			_userLogRepository = userLogRepository;
			_orderBaseRepository = orderBaseRepository;
			_memberCashCouponRepository = memberCashCouponRepository;
			_apiName = settings.Value.ApiName;
			_memberCouponRepository = memberCouponRepository;
		}
		/// <summary>
		/// Handle the specified request and cancellationToken.
		/// </summary>
		/// <returns>The handle.</returns>
		/// <param name="request">Request.</param>
		/// <param name="cancellationToken">Cancellation token.</param>
		public async Task<BaseResult<PaymentRsp>> Handle(CreateCakeOrderV2Command request, CancellationToken cancellationToken)
		{
			if (request == null) {
				throw new ArgumentNullException(nameof(request));
			}
			var storeinfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
			if (storeinfo == null) {
				return new BaseResult<PaymentRsp>(null, 9999, "门店信息有误！");
			}
			if (storeinfo.IsCakeShopClose == 1) {
				return new BaseResult<PaymentRsp>(null, 9999, "抱歉门店已闭店！");
			}
				if (storeinfo.IsCakeClose == 1) {
				return new BaseResult<PaymentRsp>(null, 9999, "抱歉门店未营业！");
			}
			if (storeinfo.IsOpenSend == 0 && request.OrderType > 1) {
				return new BaseResult<PaymentRsp>(null, 9999, " 不支持送货上门！");
			}
			var goodsbase = await this.GetGoodsByIdStoreId(storeinfo.StoreId, request.GoodsBaseId).ConfigureAwait(false);
			OrderLogger.Trace($"{JsonConvert.SerializeObject(goodsbase)}");
			if (goodsbase == null || goodsbase.Status == 0) {
				return new BaseResult<PaymentRsp>(null, -22, "产品已经下架！");
			}
		


				if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US")) < DateTime.Parse(request.TakeTime.ToString("2018-05-20 HH:mm:ss", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
					return new BaseResult<PaymentRsp>(null, -23, "抱歉该自提时间不能预定");
				}

				//if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
				//	if (request.TakeTime < DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyyy-MM-dd 23:00:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
				//		var stockreq = new ProductStockQueryReq { shopid = storeinfo.RelationId, product = new List<ProductStockReq>() };
				//		stockreq.product.Add(new ProductStockReq {
				//			pid = $"{goodsbase.GoodsRelationId}",
				//			count = request.Quantity
				//		});
				//		var zmodel = await NetICService.Productstockquery(stockreq).ConfigureAwait(false);
				//		if (zmodel != null && zmodel.product.Count > 0) {
				//			// int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(data.relationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));

				//			if (zmodel.product[0].count < request.Quantity) {
				//				return new BaseResult<PaymentRsp>(null, -21, "库存不足");
				//			}
				//		} else {
				//			return new BaseResult<PaymentRsp>(null, -21, "库存不足");
				//			//logger.Error($"buynowerror:{JsonConvert.SerializeObject(dto)},{JsonConvert.SerializeObject(zmodel)}");
				//			//return Ok(new { code = -22, msg = "产品已经下架" });
				//		}
				//	}
				//}
			



			var cardlist = await _memberCardRepository.GetListAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			var _cardno = "";
			var _cardtype = 1;
			if (cardlist != null && cardlist.Count(c => c.IsBind == true) == 2) {
				var vipcard = cardlist.SingleOrDefault(c => c.IsBind == true && c.CardType != "3");
				if (vipcard != null) {
					_cardno = vipcard.CardNO;
				}
			}
			if (string.IsNullOrEmpty(request.PayCardNO)) {
				foreach (var item in cardlist) {
					if (item.IsBind) {
						_cardno = item.CardNO;
						_cardtype = item.CardType.ToInt16(1);
						break;
					}
				}
			} else {
				var cardinfo = cardlist.Find(c => c.CardNO == request.PayCardNO);
				if (cardinfo != null) {
					_cardtype = cardinfo.CardType.ToInt16(1);
				}
				_cardno = request.PayCardNO;
			}
			var goodbase = await GetGoodsByIdStoreId(request.StoreId, request.GoodsBaseId).ConfigureAwait(false);
			if (goodbase == null || goodbase.Status == 0) {
				return new BaseResult<PaymentRsp>(null, -22, "产品已经下架");
			}
			if (request.TakeTime < DateTime.Now) {
				return new BaseResult<PaymentRsp>(null, -25, "自提时间有误");
			}
			if (storeinfo.IsLimitStock == 0) {
				if (goodbase.StockDays > 1) {
					if (request.TakeTime.DayOfYear != DateTime.Now.DayOfYear) {
						if (request.TakeTime < DateTime.Parse(DateTime.Now.AddDays(goodbase.StockDays).ToString("yyyy-MM-dd 00:00:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
							return new BaseResult<PaymentRsp>(null, -28, "本款蛋糕需提前2天预定");
						}
					}
				}
			}
			//if (DateTime.Parse(DateTime.Now.ToString("2018-05-20 20:30:00")) < DateTime.Parse(request.TakeTime.ToString("2018-05-20 HH:mm:ss")))
			//{
			//    return new BaseResult<PaymentRsp>(null, -23, "抱歉该自提时间不能预定");
			//}
			//if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00")) && data.picktime.DayOfYear == DateTime.Now.AddDays(1).DayOfYear)
			//{
			//    return Ok(new { code = -23, msg = "抱歉该时间段不能预定次日蛋糕" });
			//}

			//ProductStockQueryReq req = new ProductStockQueryReq { shopid = storeinfo.RelationId, datasource = $"{request.DataSource}024".ToInt16(0), product = new List<ProductStockReq>() };
			//req.product.Add(new ProductStockReq { pid = $"{goodbase.GoodsRelationId}", count = request.Quantity });

			//if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
			//	if (request.TakeTime < DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyyy-MM-dd 23:00:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US"))) {
			//		var zmodel = await NetICService.Productstockquery(req).ConfigureAwait(false);
			//		if (zmodel != null && zmodel.product.Count > 0) {
			//			// int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(goodbase.GoodsRelationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));

			//			if (zmodel.product[0].count < request.Quantity) {
			//				return new BaseResult<PaymentRsp>(null, -21, "库存不足");
			//			}
			//		} else {
			//			return new BaseResult<PaymentRsp>(null, -21, "库存不足");

			//		}
			//	}
			//}
			if (request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
				if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 20:30:00", CultureInfo.CreateSpecificCulture("en-US")), CultureInfo.CreateSpecificCulture("en-US")) && request.TakeTime.DayOfYear == DateTime.Now.DayOfYear) {
					return new BaseResult<PaymentRsp>(null, -23, "抱歉该时间段不能预定当天蛋糕自提");
				}
				//if (storeinfo.IsLimitStock == 0) {
				//	var zmodel = await NetICService.Productstockquery(req).ConfigureAwait(false);
				//	if (zmodel != null && zmodel.product.Count > 0) {
				//		// int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(goodbase.GoodsRelationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));

				//		if (zmodel.product[0].count < request.Quantity) {
				//			return new BaseResult<PaymentRsp>(null, -21, "库存不足");
				//		}
				//	} else {
				//		return new BaseResult<PaymentRsp>(null, -21, "库存不足");

				//	}
				//}
			}
			string discountCouponName = "";

			string TicketCode = "";
			for (int i = 0; i < request.DiscountList.Count; i++) {
				var discontitem = request.DiscountList[i];
				if (discontitem.DiscountCouponType == 1) {
					if (discontitem.DiscountCouponId > 0) {
						var ticketreq = new GetTicticketReq { Cardno = _cardno, Pagesize = 200, State = 2, Pageindex = 1 };
						Iclogger.Trace($"GeticticketReq:{JsonConvert.SerializeObject(ticketreq)}");
						var a = await NetICService.Geticticket(ticketreq).ConfigureAwait(false);
						if (a.code == 0) {
							var list = JsonConvert.DeserializeObject<TicketItemRoot>(a.content);
							var ticket = list.Tickets.SingleOrDefault(t => t.Ticketid == discontitem.DiscountCouponId);
							if (ticket != null) {
								request.DiscountList[i].DiscountCouponMoney = ticket.Je.ToDecimal(0);
								discountCouponName = ticket.Ticketname;
							} else {
								return new BaseResult<PaymentRsp>(null, -23, "优惠券不可用");
							}
							if ((request.Paymethod == 3) && (_cardtype == 3)) {
								return new BaseResult<PaymentRsp>(null, -41, "优惠券不能与幸福卡同时使用");
							}
						} else {
							return new BaseResult<PaymentRsp>(null, -23, "优惠券不可用");
						}

						var tt = new List<long>() { discontitem.DiscountCouponId };
						var ticketLimit = await NetICService.TicketLimit(storeinfo.RelationId, tt, 1, true).ConfigureAwait(false);


						if (ticketLimit.code == 0) {
							var d = JsonConvert.DeserializeObject<TicketsRules>(ticketLimit.content);
							if (d != null && d.Tickets.Any()) {

								var list216 = d.Tickets.Where(c => c.Limittype == 216);
								if (list216.Any()) {
									bool s = false;
									var list216msg = "";
									foreach (var item in list216) {
										if (goodsbase.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture)) {

											s = true;
										} else {
											list216msg += $"{item.Productname}{item.Limitdesc}";
										}
									}
									if (!s) {
										return new BaseResult<PaymentRsp>(null, -23, list216msg);
									}
								}

								var list215 = d.Tickets.Where(c => c.Limittype == 215);
								if (list215.Any()) {
									var list215sucess = true;
									var amsg = "";
									foreach (var item in list215) {
										if (goodsbase.GoodsRelationId != int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture)) {
											amsg += $"{item.Productname}{item.Limitdesc}";
											list215sucess = false;
										}
									}
									if (!list215sucess) {
										return new BaseResult<PaymentRsp>(null, -23, amsg);
									}

								}

								foreach (var item in d.Tickets) {
									if (item.Limittype == 51) {
										var tamount = goodsbase.Price * request.Quantity;

										if (tamount < item.Limitvalue.ToDecimal(0)) {
											return new BaseResult<PaymentRsp>(null, -23, $"{item.Productname}{item.Limitdesc}");
										}
									}
									if (item.Limittype == 22) {
										if (goodsbase.GoodsRelationId == int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture)) {
											return new BaseResult<PaymentRsp>(null, -23, $"{item.Productname}{item.Limitdesc}");
										}

									}
									if (item.Limittype == 21) {
										if (goodsbase.GoodsRelationId != int.Parse(item.Limitvalue, System.Globalization.CultureInfo.CurrentCulture)) {
											return new BaseResult<PaymentRsp>(null, -23, $"{item.Productname}{item.Limitdesc}");
										}

									}
								}
							}
						}
					}

				} else if (discontitem.DiscountCouponType == 2) {

					if (_apiName == "hgspApi") {
						var tlist = await _memberCashCouponRepository.GetListAsnyc<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
						if (!tlist.Any()) {
							return new BaseResult<PaymentRsp>(null, 999, "代金券有误");
						}
						MemberCashCoupon cashentity = tlist.SingleOrDefault(t => t.TicketCode.Contains($"{discontitem.DiscountCouponId}", StringComparison.OrdinalIgnoreCase));
						if (cashentity == null) {
							return new BaseResult<PaymentRsp>(null, 999, "代金券有误");
						}
						if (cashentity.State == 4) {
							return new BaseResult<PaymentRsp>(null, 999, "代金券使用中");
						}
						TicketCode = cashentity.TicketCode;


						//var cashentity = await _memberCashCouponRepository.GetKeyAsync<ICasaMielSession>($"{discontitem.DiscountCouponId}").ConfigureAwait(false);
						//if (cashentity == null || (cashentity.Mobile != request.Mobile))
						//{
						//    return new BaseResult<PaymentRsp>(null, 999, "代金券有误");
						//}
						//if (cashentity.State == 4)
						//{
						//    return new BaseResult<PaymentRsp>(null, 999, "代金券使用中");
						//}

						var rsp = await NetICService.Tmticketquery(new TmticketqueryReq { ticketcode = cashentity.TicketCode }).ConfigureAwait(false);
						if (rsp.code == 0) {
							var d = JsonConvert.DeserializeObject<JObject>(rsp.content);
							var memberCashCoupon = new MemberCashCoupon {
								TicketCode = cashentity.TicketCode,
								Mobile = request.Mobile,
								State = (int)d["state"],
								CouponName = d["productname"].ToString(),
								CreateTime = DateTime.Now,
								EndDate = (DateTime)d["enddate"],
								StartDate = (DateTime)d["startdate"],
								Price = (decimal)d["price"]
							};
							if (memberCashCoupon.State != 3) {
								return new BaseResult<PaymentRsp>(null, 999, "代金券" + d["description"].ToString());
							}
						} else {
							return new BaseResult<PaymentRsp>(null, rsp.code, rsp.msg);
						}
					}
					else {
						var couponentity = await _memberCouponRepository.GetKeyAsync<ICasaMielSession>(discontitem.DiscountCouponId).ConfigureAwait(false);
                       

                        if (couponentity == null) {
							return new BaseResult<PaymentRsp>(null, 999, "代金券有误");
						}

						var rsp = await NetICService.Tmticketquery(new TmticketqueryReq { ticketcode = couponentity.Ticketcode }).ConfigureAwait(false);
						if (rsp.code == 0) {
							var d = JsonConvert.DeserializeObject<JObject>(rsp.content);
                            TicketCode = couponentity.Ticketcode;
                            //var memberCashCoupon = new MemberCashCoupon {
                            //	TicketCode = couponentity.Ticketcode,
                            //	Mobile = request.Mobile,
                            //	State = (int)d["state"],
                            //	CouponName = d["productname"].ToString(),
                            //	CreateTime = DateTime.Now,
                            //	EndDate = (DateTime)d["enddate"],
                            //	StartDate = (DateTime)d["startdate"],
                            //	Price = (decimal)d["price"]
                            //};
                            if ((int)d["state"] != 3) {
								return new BaseResult<PaymentRsp>(null, 999, "代金券" + d["description"].ToString());
							}
						} else {
							return new BaseResult<PaymentRsp>(null, rsp.code, rsp.msg);
						}
					}
				}
			}
			if (request.Paymethod == 3) {
				if (string.IsNullOrEmpty(request.PayCardNO)) {
					return new BaseResult<PaymentRsp>(null, 999, "卡号不能为空");
				}
				var zcard = await NetICService.Iclessquery(request.PayCardNO, $"{request.Source}099".ToInt32(0)).ConfigureAwait(false);//.GetCardBalance(data.Paycardno);
				if (zcard.code == 0) {
					var cardinfo = JsonConvert.DeserializeObject<JObject>(zcard.content);
					var balance = cardinfo["totalmoney"].ToDecimal(0);
					if ((balance + request.DiscountList.Sum(c => c.DiscountCouponMoney)) < (goodbase.Price * request.Quantity)) {
						if (_cardtype == 3)//幸福卡
						{
							return new BaseResult<PaymentRsp>(null, -40, "卡内余额不足");
						}
						return new BaseResult<PaymentRsp>(null, -39, "卡内余额不足");
					}
				} else {
					return new BaseResult<PaymentRsp>(null, zcard.code, zcard.msg);
				}
			}

			//  var billNO = "";

			if (request.OrderType == 2) {
				if (request.ConsigneeId == 0) {
					return new BaseResult<PaymentRsp>(null, -30, "收货地址不能空");
				}
				if (storeinfo.IsOpenSend == 0) {
					return new BaseResult<PaymentRsp>(null, 9999, "门店不支持送货上门");
				}
				var info = await CheckLocation(request.StoreId, request.ConsigneeId).ConfigureAwait(false);
				var inforesult = JsonConvert.DeserializeObject<JObject>(info);
				if (inforesult["resultNo"].ToString() != "00000000") {
					return new BaseResult<PaymentRsp>(null, -28, inforesult["resultRemark"].ToString());
				}
			}

			var icdto = new IcconsumeReq { Phoneno = request.Mobile, Cardno = _cardno, Shopid = storeinfo.RelationId, Pickuptime = request.TakeTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture) };
			icdto.Product = new List<IcconsumeReq.IcconsumeProductItem>
			{
				new IcconsumeReq.IcconsumeProductItem { Pid = $"{goodbase.GoodsRelationId}", Count = request.Quantity }
			};
			var icentity = await NetICService.Icconsume(icdto).ConfigureAwait(false);
			if (icentity.code == 0) {
				var jobject = JsonConvert.DeserializeObject<JObject>(icentity.content);
				request.IcTradeNO = jobject["tradeno"].ToString();
				request.BillNo = jobject["billno"].ToString();
			} else {
				return new BaseResult<PaymentRsp>(null, icentity.code, icentity.msg);
			}

			var backreq = new IcConsumeBackReq { Tradeno = request.IcTradeNO };
			OrderCreateRsp order;
			try {
				OrderLogger.Trace(JsonConvert.SerializeObject(request));
				var url = "CakeMall/v3/Order/Create";

				var result = await PostThirdApiAsync<OrderCreateRsp>(url, JsonConvert.SerializeObject(request)).ConfigureAwait(false);
				OrderLogger.Trace(result);
				// var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
				if (result.Code == 0) {
					order = result.Content;// JsonConvert.DeserializeObject<Order_CreateRsp>(dynamicdata["data"].ToString());
					var itemlist = request.DiscountList.Where(c => c.DiscountCouponType == 2).ToList();

					itemlist.ForEach(async a => {
						var cashentity = await _memberCashCouponRepository.GetKeyAsync<ICasaMielSession>($"{a.DiscountCouponId}").ConfigureAwait(false);
						if (cashentity != null) {
							cashentity.State = 4;
							await _memberCashCouponRepository.UpdateAsync<ICasaMielSession>(cashentity).ConfigureAwait(false);
						}
					});

				} else {
					var d = await NetICService.Icconsumeback(backreq).ConfigureAwait(false);
					OrderLogger.Error($"{JsonConvert.SerializeObject(backreq)},{JsonConvert.SerializeObject(d)}");
					BizInfologger.Error($"{url},{JsonConvert.SerializeObject(request)},{JsonConvert.SerializeObject(result)}");
					return new BaseResult<PaymentRsp>(null, 9999, result.Msg);
				}
			} catch (System.Net.Sockets.SocketException ex) {
				var d = await NetICService.Icconsumeback(backreq).ConfigureAwait(false);
				OrderLogger.Error($"{JsonConvert.SerializeObject(backreq)},{JsonConvert.SerializeObject(d)}");
				OrderLogger.Error(ex.StackTrace);
				//if (order != null)
				//{
				//    var result = await PostAsync("TPP/v1/Order/Delete", JsonConvert.SerializeObject(new { order.OrderCode }));
				//    logger.Error($"{result}");
				//}

				throw;
			}
			//优惠券
			if (order.PayMoney == 0) {
				request.Paymethod = 3;
			}
			
			//var entity = await _storeService.GetByOrderCodeAsync<ICasaMielSession>(order.OrderCode, mobile);

			var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CreateSpecificCulture("en-US"))}";
			var payment = new PaymentRecord {
				OperationMethod = 2,
				TradeNo = p_tradeno,
				Amount = $"{order.PayMoney}".ToDouble(0),
				PayMethod = request.Paymethod,
				BillNO = order.OrderCode,
				IcTradeNO = request.IcTradeNO,
				State = 0,
				OperationState = 0,
				CreateTime = DateTime.Now,
				Mobile = request.Mobile
			};
			switch (request.Paymethod) {
				case 3://会员卡
					var pay = new IcConsumepayReq {
						Phoneno = request.Mobile,
						Cardno = request.PayCardNO,
						Shopid = storeinfo.RelationId,
						Tradeno = request.IcTradeNO,
						Createinvoice = true
					};
					pay.Paycontent = new List<IcConsumepayReq.PaycontentItem>
					{
						new IcConsumepayReq.PaycontentItem
						{
							Paytype = "3",
							Paymoney = $"{order.OrderMoney }".ToDouble(0),
							Paytradeno = $"c{DateTime.Now.ToString("yyMMddHHmmssffff",CultureInfo.CreateSpecificCulture("en-US"))}"
						}
					};
					//只能二选一
					request.DiscountList.ForEach((Action<OrderDiscountReq>)(x => {
						var _paytype = "5";
						var payuser = $"{x.DiscountCouponId}";
						if (x.DiscountCouponType == 1)
						{
	   _paytype = "6";
						} else {
							payuser = TicketCode;
						}

						pay.Paycontent.Add(new IcConsumepayReq.PaycontentItem {
							Paytype = _paytype,
							Paymoney = $"{ x.DiscountCouponMoney}".ToDouble(0),
							Paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff", CultureInfo.CreateSpecificCulture("en-US"))}",
							Payuser = payuser
						});
					}));

					//if (request.DiscountCouponId > 0)
					//{
					//    pay.paycontent.Add(new IcConsumepayReq.Paycontent
					//    {
					//        paytype = "6",
					//        paymoney = request.DiscountCouponMoney.ToString().ToDouble(0),
					//        paytradeno = $"t{DateTime.Now.ToString("yyMMddHHmmssffff")}",
					//        payuser = $"{request.DiscountCouponId}"
					//    });
					//}


					var zmodel = await NetICService.Icconsumepay(pay).ConfigureAwait(false);
					if (zmodel.code == 0) {
						var jobject = JsonConvert.DeserializeObject<JObject>(zmodel.content);
						if (jobject != null && jobject["invoiceqrcode"] != null) {
							var invoiceUrl = jobject["invoiceqrcode"].ToString();
							await _orderBaseRepository.UpdateOrderInvoiceUrlByOrderCodeAsync<ICasaMielSession>(payment.BillNO, invoiceUrl).ConfigureAwait(false);
						} else {
							BizInfologger.Error($"Invoideurl:{zmodel.content}");
						}

						using (var uow = _session.UnitOfWork(IsolationLevel.Serializable)) {

							payment.State = 1;
							payment.Remark = $"会员卡：{request.PayCardNO}";
							payment.OperationState = 1;
							payment.PayTime = DateTime.Now;
							await _paymentRecordRepository.SaveAsync(payment, uow).ConfigureAwait(true);
							var noticEntity = new NoticeBaseEntity() {
								RemindTime = DateTime.Now.AddMinutes(-3),
								CreateTime = DateTime.Now,
								RelationId = order.OrderBaseId,
								StoreId = request.StoreId,
								NoticeType = 0
							};
							await _noticeBase.SaveAsync(noticEntity, uow).ConfigureAwait(true);
						}
						var logdata = new UserLog { Url = request.RequestUrl, OPInfo = $"蛋糕订单支付,卡号:[{request.PayCardNO},支付金额{order.PayMoney}，订单号：{order.OrderCode}", OPTime = DateTime.Now, UserName = request.Mobile };
						await _userLogRepository.SaveAsync<ICasaMielSession>(logdata).ConfigureAwait(false);

						await CakeOrderChangeStatus(order.OrderCode, request.Mobile, 1, request.Paymethod, "").ConfigureAwait(false);
						var p = new PaymentRsp { Payed = true, PayMethod = 3, Paymentrequest = "", OrderCode = order.OrderCode };
						return new BaseResult<PaymentRsp>(p, 0, "");
					} else {
						return new BaseResult<PaymentRsp>(null, zmodel.code, zmodel.msg);
					}

				default:

					var pp = new PaymentRsp { Payed = false, PayMethod = request.Paymethod, Paymentrequest = $"{order.PayMoney},{request.IcTradeNO}", OrderCode = order.OrderCode };

					return new BaseResult<PaymentRsp>(pp, 0, "");

			}

		}


		private async Task<string> CheckLocation(int StoreId, int ConsigneeId)
		{
			var url = "CakeMall/v1/Address/CheckLocation";
			var data = new { StoreId, ConsigneeId };
			return await PostAsync(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
		}

	}
}
